package com.chen.authority.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.chen.authority.common.response.SingleResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 缓存监控
 *
 * @author chengy
 * @date 2022/11/19
 */
@Api(tags = "缓存监控 CacheController")
@RequiredArgsConstructor
@RestController
public class CacheController {

    private final RedisTemplate<String, String> redisTemplate;

    /**
     * 获取redis状态
     *
     * @return SingleResponse<Map < String, Object>>
     */
    @ApiOperation("获取redis状态")
    @SaCheckPermission("monitor:cache:get")
    @GetMapping("/monitor/cache")
    public SingleResponse<Map<String, Object>> getRedisInfo() {
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::info);
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::dbSize);

        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.getProperty(key);
            data.put("name", StringUtils.removeStart(key, "cmdstat_"));
            data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });

        result.put("commandStats", pieList);

        return SingleResponse.success(result);
    }

}
